package cn.com.yinhex.as.util;

import java.io.File;

public class UrlCache extends Thread {

	public static String cachedir = "/tmp/cache/";

	String url = "";

	String tempfile = "";

	String encoding = "";

	boolean isdownload = false;

	public boolean downloaded = false;

	long millisecond = 0L;

	public UrlCache(String url, String tempfile, String encoding, long millisecond) {
		this.url = url;
		this.tempfile = tempfile;
		this.millisecond = millisecond;
		this.encoding = encoding;
	}

	public void run() {
		if (System.currentTimeMillis() - FileUtil.getFileTime(tempfile) > millisecond) {
			downloaded = true;
			new File(tempfile).setLastModified(System.currentTimeMillis());
			if (url.indexOf("?") > -1) {
				url = url + "&" + System.currentTimeMillis();
			} else {
				url = url + "?" + System.currentTimeMillis();
			}
			if (this.isdownload) {
				NetUtil.download(url, tempfile);
			} else {
				String html = NetUtil.readURL(url, encoding, "\n");
				if (StringUtil.isFine(html)) {
					if (html.charAt(0) == 65279) {
						html = html.substring(2);
					}
					FileUtil.write(tempfile, html);
				} else {
					FileUtil.write(tempfile, "");
				}
			}
			// System.out.println("tempfile: " + tempfile);
		}
	}

	public void setDownload(boolean isdownload) {
		this.isdownload = isdownload;
	}

	public boolean getDownloaded() {
		return downloaded;
	}
}
